﻿<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />

    <title>拖拽-磁性吸附</title>
    <style>
      * {
        margin: 0;
        padding: 0;
        list-style: none;
        font-family: "微软雅黑", "张海山锐线体简";
      }

      #div1 {
        width: 200px;
        height: 200px;
        background: red;
        left: 0;
        top: 0;
        position: absolute;
      }
    </style>
    <script>
      window.onload = function() {
        var oDiv = document.getElementById("div1");
        oDiv.onmousedown = function(ev) {
          var oEvt = ev || event;
          var disX = oEvt.clientX - oDiv.offsetLeft;
          var disY = oEvt.clientY - oDiv.offsetTop;
          document.onmousemove = function(ev) {
            var oEvt = ev || event;
            var l = oEvt.clientX - disX; //计算
            var t = oEvt.clientY - disY;
            //限定
            if (l < 50) l = 0;
            if (l > document.documentElement.clientWidth - oDiv.offsetWidth - 50) l = document.documentElement.clientWidth - oDiv.offsetWidth;
            if (t < 50) t = 0;
            if (t > document.documentElement.clientHeight - oDiv.offsetHeight - 50) t = document.documentElement.clientHeight - oDiv.offsetHeight;

            oDiv.style.left = l + "px"; //使用
            oDiv.style.top = t + "px";
          };
          document.onmouseup = function() {
            document.onmouseup = document.onmousemove = null;
            oDiv.releaseCapture && oDiv.releaseCapture();
          };
          oDiv.setCapture && oDiv.setCapture();
          return false;
        };
      };
    </script>
  </head>

  <body>
    <div id="div1">asdfasdfsdf <img src="m1.jpg" width="50" /></div>
  </body>
</html>
